
Ext.define('Writer.Form', {
    extend: 'Ext.form.Panel',
    alias: 'widget.writerform',

    requires: ['Ext.form.field.Text'],

    initComponent: function(){
        Ext.apply(this, {
            activeRecord: null,
            iconCls: 'icon-user',
            frame: true,
            title: 'ADMINISTRACION DE USUARIOS',
            defaultType: 'textfield',
            bodyPadding: 25,
            fieldDefaults: {
                anchor: '100%',
            },
            items: [{
                fieldLabel: 'Id',
                hidden: true,
                name: 'id',
                type: 'int',
            },{
                fieldLabel: 'Nombre Usuario',
                name: 'nombreUsuario',
                allowBlank: false               
				
            },{
                fieldLabel: 'Nombre',
                name: 'nombre',
            }, {
                fieldLabel: 'Apellido',
                name: 'apellido',
            }, {
                fieldLabel: 'Telefono',
                name: 'telefono',
                type: 'int',
            }, {
                fieldLabel: 'Nº Documento',
                name: 'nroDocumento',
                type: 'int',
            },{
                fieldLabel: 'Email',
                name: 'email',
                allowBlank: false,
                vtype: 'email'
            },{
                fieldLabel: 'Password',
                name: 'password1',
                itemId: 'f_password1',
                hidden: true,
                disabled: true,                
				inputType: 'password',
            }],
            dockedItems: [{
                xtype: 'toolbar',
                dock: 'bottom',
                items: ['->', {
                    iconCls: 'icon-rol',
                    itemId: 'rol',
                    text: 'Roles',
                    tooltip:'Asignar - Desasignar Roles al usuario seleccionado',
                    hidden: true,
                    disabled: true,
                    scope: this, 
                    handler: this.onRol
                },{
                    iconCls: 'icon-user-delete',
                    itemId: 'delete',
                    hidden: true,
                    disabled: true,
                    scope: this, 
                    text: 'Eliminar',
                    tooltip:'Eliminar el usuario seleccionado',
                    scope: this,
                    handler: this.onDelete
                },{
                    iconCls: 'icon-save',
                    itemId: 'save',
                    text: 'Guardar',
                    tooltip:'Modificar el usuario seleccionado',
                    hidden: true,
                    disabled: true,
                    scope: this, 
                    handler: this.onSave
                },  {
                    iconCls: 'icon-user-add',
                    itemId: 'create',
                    text: 'Crear',
                    tooltip:'Crear un usuario nuevo',
                    disabled: true,
                    hidden: true,
                    scope: this,
                    handler: this.onCreate
                }, {
                    iconCls: 'icon-reset',
                    text: 'Reset',
                    tooltip:'Resetear el formulario',
                    scope: this,
                    handler: this.onReset
                }]
            }]
        });
        this.callParent();
    },

    setActiveRecord: function(record){
        this.activeRecord = record;
        if (record) {
            if (!this.down('#save').isDisabled()){
				this.down('#save').show();			
			}			
            if (!this.down('#delete').isDisabled()){
				this.down('#delete').show();			
			}
            if (!this.down('#rol').isDisabled()){
				this.down('#rol').show();			
			}			
            this.down('#create').hide(); 
            this.down('#f_password1').hide(); 
                       
            this.getForm().loadRecord(record);
        } else {
            this.down('#save').hide();
            this.down('#delete').hide();
            this.down('#rol').hide();
            if (!this.down('#create').isDisabled()){
				this.down('#create').show();			
			} 
            if (!this.down('#f_password1').isDisabled()){
				this.down('#f_password1').show();			
			}  			           
            this.getForm().reset();
        }
    },

    onSave: function(){
        var form = this.getForm();

                    form.submit({
                        
                        url: 'modificarUsuarios',
                        params: {
								submit: 'submit'
						},
						method: "post",
                        success: function(form, action) {
								form.reset();
							    Ext.Msg.show({  
									title: '<br><p align="center"><b>ALPHA MANAGER</b></p>', //<- el título del diálogo  
									msg: 'Usuario modificado satisfactoriamente', //<- El mensaje  
									icon: 'ext-mb-ok',

								});
							this.fireEvent('refresh');
							                       
                        },
                        scope: this,
                        failure: function(form, action) {
									Ext.Msg.show({  
										title: '<br><p align="center"><b>ALPHA MANAGER</b></p>', //<- el título del diálogo  
										msg: 'No se ha podido modificar el usuario', //<- El mensaje  
										icon: 'ext-mb-error',

									});
                        }
                    });

    },

    onCreate: function(){
        var form = this.getForm();

                    form.submit({
                        
                        url: 'crearUsuarios',
                        params: {
								submit: 'submit'
						},
						method: "post",
                        success: function(form, action) {
								form.reset();
							    Ext.Msg.show({  
									title: '<br><p align="center"><b>ALPHA MANAGER</b></p>', //<- el título del diálogo  
									msg: 'Usuario creado satisfactoriamente', //<- El mensaje  
									icon: 'ext-mb-ok',

								});
							this.fireEvent('refresh');
							                       
                        },
                        scope: this,
                        failure: function(form, action) {
									Ext.Msg.show({  
										title: '<br><p align="center"><b>ALPHA MANAGER</b></p>', //<- el título del diálogo  
										msg: 'No se ha podido crear el usuario', //<- El mensaje  
										icon: 'ext-mb-error',

									});
                        }
                    });


    },

    onDelete: function(){ 
        var form = this.getForm();

                    form.submit({
                        
                        url: 'eliminarUsuarios',
                        params: {
								submit: 'submit'
						},
						method: "post",
                        success: function(form, action) {
								form.reset();
							    Ext.Msg.show({  
									title: '<br><p align="center"><b>ALPHA MANAGER</b></p>', //<- el título del diálogo  
									msg: 'Usuario eliminado satisfactoriamente', //<- El mensaje  
									icon: 'ext-mb-ok',

								});
							this.fireEvent('refresh');
							                       
                        },
                        scope: this,
                        failure: function(form, action) {
									Ext.Msg.show({  
										title: '<br><p align="center"><b>ALPHA MANAGER</b></p>', //<- el título del diálogo  
										msg: 'No se ha podido eliminar el usuario', //<- El mensaje  
										icon: 'ext-mb-error',

									});
                        }
                    });


    },
	onRol: function(){
			var form = this.getForm();
			this.fireEvent('roles', form.getValues(true));
            
	},

    onReset: function(){
        this.setActiveRecord(null);
        this.getForm().reset();
        this.fireEvent('refresh'); 
    },
  
    
});

Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('Ext.ux', 'static/ux');

Ext.define('Writer.Grid', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.writergrid',

    requires: [
        'Ext.grid.plugin.CellEditing',
        'Ext.form.field.Text',
        'Ext.ux.grid.FiltersFeature',
        'Ext.toolbar.TextItem'
    ],

    initComponent: function(){

        this.editing = Ext.create('Ext.grid.plugin.CellEditing');
        
        var filters = {
			ftype: 'filters',
			local: true,

		};


        Ext.apply(this, {
            iconCls: 'icon-grid',
            //frame: true,
            plugins: [this.editing],
            features: [filters],
            dockedItems: [{ //toolbar para filtrado	falta
                weight: 1,
                xtype: 'toolbar',
                dock: 'bottom',
                items: ['->', {
                    iconCls: 'icon-lista',
                    text: 'Listar',
                    tooltip:'Para listado perzonalizado, configure los filtros de las columnas',
                    scope: this,
                    handler: this.onListar
                }, {
                    iconCls: 'icon-refresh',
                    text: 'Actualizar',
                    tooltip:'Actualizar la lista',
                    scope: this,
                    handler: this.onRefresh
                }]
            }],
            columns: [{
                text: 'Id',
                width: 40,
                filter: true,
                dataIndex: 'id'
            },{
                header: 'Nombre Usuario',
                flex: 1,
                //width: 90,
                filter: true,
                dataIndex: 'nombreUsuario',

            },{
                header: 'Nombre',
                flex: 1,
                filter: true,
                dataIndex: 'nombre',

            }, {
                header: 'Apellido',
                flex: 1,
                filter: true,
                dataIndex: 'apellido',

            },{
                text: 'Telefono',
                flex: 1,
                //width: 60,
                filter: true,              
                dataIndex: 'telefono'
            },{
                text: 'Nº Documento',
                flex: 1,
                filter: true,
                dataIndex: 'nroDocumento'
            }, {
                header: 'Email',
                width: 150,
                filter: true,
                dataIndex: 'email',

            },{
                header: 'Fecha Creacion',
                flex: 1,
                //width: 100,
                filter: true,
                dataIndex: 'fecha',

            }]
        });
        this.callParent();
        this.getSelectionModel().on('selectionchange', this.onSelectChange, this);
    },
    
    onListar: function(){
		this.getSelectionModel().clearSelections();
		this.store.load();
    },

    onRefresh: function(){
		this.getSelectionModel().clearSelections();
		this.store.load();
    }
});

Ext.define('Writer.Person', {
    extend: 'Ext.data.Model',
    fields: [{
        name: 'id',
        type: 'int',
        useNull: true
    },{
        name: 'nroDocumento',
        type: 'int',
    },{
        name: 'telefono',
        type: 'int',
    }, 'email', 'nombre', 'apellido', 'nombreUsuario', 'fecha'],
    validations: [{
        type: 'length',
        field: 'email',
        min: 1
    }, {
        type: 'length',
        field: 'first',
        min: 1
    }, {
        type: 'length',
        field: 'last',
        min: 1
    }, {
        type: 'length',
        field: 'nombreUsuario',
        min: 1
    }]
});



Ext.require([
    'Ext.data.*',
    'Ext.tip.QuickTipManager',
    'Ext.window.MessageBox',
    'Ext.grid.*',
    'Ext.tab.*',
    'Ext.window.*',
    'Ext.tip.*',
    'Ext.layout.container.Border',
    'Ext.dd.*',
    'Ext.form.field.ComboBox',
    'Ext.form.FieldSet'
]);


Ext.define('DataObject', {
    extend: 'Ext.data.Model',
    fields: ['nombreRol']
});

Ext.onReady(function(){
    Ext.tip.QuickTipManager.init();
    
		function getPermisos()
		{
			Ext.Ajax.request({
					url: 'listarPermisos_Logueado',
					method: 'GET',
					success: function(response) {
						var jsonData = Ext.JSON.decode(response.responseText);
						var resultMessage = jsonData['data'];
						if(extraer(resultMessage,'{','crear-usuario')){	
							win.child('#form').down('#create').enable();
							win.child('#form').down('#create').show();
							win.child('#form').down('#f_password1').enable();
							win.child('#form').down('#f_password1').show();								
												
						}
						if(extraer(resultMessage,'{','eliminar-usuario')){	
							win.child('#form').down('#delete').enable();
							
						}
						if(extraer(resultMessage,'{','modificar-usuario')){	
							win.child('#form').down('#save').enable();
							
						}
						if(extraer(resultMessage,'{','asignar-desasignar-rol')){	
							win.child('#form').down('#rol').enable();
							
						}												
						
					}/*,
					failure: function() {
						Ext.Msg.alert('Alpha Manager','No se obtuvieron los permisos')
												
					}*/
			});
		}
	
    var storeRol = Ext.create('Ext.data.Store', {
        model: 'modeloRol',
        autoLoad: true,
        proxy: {
            type: 'ajax',
            url: 'listarRoles',
            reader: {
                type: 'json',
                successProperty: 'success',
                root: 'data',
                messageProperty: 'message'
            },
            writer: {
                type: 'json',
                writeAllFields: false,
                root: 'data'
            },

        }        
        
    });
    
    var store = Ext.create('Ext.data.Store', {
        model: 'Writer.Person',
        //autoLoad: true,
        //autoSync: true,
        proxy: {
            type: 'ajax',
            url: 'listarUsuarios',
            reader: {
                type: 'json',
                successProperty: 'success',
                root: 'data',
                messageProperty: 'message'
            },
            writer: {
                type: 'json',
                writeAllFields: false,
                root: 'data'
            },

        },
        listeners: {
            write: function(proxy, operation){
                if (operation.action == 'destroy') {
                    main.child('#form').setActiveRecord(null);
                }
                Ext.example.msg(operation.action, operation.resultSet.message);
            }
        },
        
        sorters: [{
            property: 'id',
            direction: 'ASC'
        }]        
    });
   
			win = Ext.create('widget.panel', {
				renderTo: 'comboUsuarios',
                width: 1200,
                height: 380,
                layout: 'border',
                //bodyStyle: 'padding: 3px;',
				y: 30,
				x: 75,
                items: [{
                    region: 'west',
					xtype: 'writerform',
					itemId: 'form',
					width: 360,
					listeners: {
						refresh: function() {
							win.child('#grid').onRefresh();
							
						},
						roles: function(data){
							var grid1, grid2;
							nombre = extraer(data, '&nombreUsuario=', '&nombre=');		id = extraer(data, 'id=', '&');
							//Ext.Msg.alert(id);
                            win2 = Ext.create('widget.window', {
								iconCls: 'icon-rol',
								title: 'Drag and Drop - Asignar/Desasignar roles al usuario: ' + nombre,
								closable: true,
								plain: true,
								layout: 'fit',
								items: [displayPanel = Ext.create('Ext.Panel', {
											width : 550,	height : 250,
											layout  : {	type: 'hbox',	align: 'stretch'	},
											defaults  : { flex : 1 }, 
											items : [
													grid1 = Ext.create('Ext.grid.Panel', {
														multiSelect: true,
														viewConfig: {
															plugins: {
																	ptype: 'gridviewdragdrop',
																	dragGroup: 'firstGridDDGroup',
																	dropGroup: 'secondGridDDGroup'
															},
														},
														store: Ext.create('Ext.data.Store', {
																	model: 'DataObject',
																	autoLoad: true,
																	proxy: {
																		type: 'ajax',
																		url: 'listarNoRoles_Usuario/'+ id,
																		reader: {
																			type: 'json',
																			successProperty: 'success',
																			root: 'data',
																			messageProperty: 'message'
																		},
																	
																	}      
																}),
														columns:  [ {text: "<b>Roles No Asignados</b>", flex: 1, sortable: true, dataIndex: 'nombreRol'} ],
														stripeRows : true
													}),
													grid2 = Ext.create('Ext.grid.Panel', {
														multiSelect: true,
														viewConfig: {
															plugins: {
																	ptype: 'gridviewdragdrop',
																	dragGroup: 'secondGridDDGroup',
																	dropGroup: 'firstGridDDGroup'
																},
														},
														store: Ext.create('Ext.data.Store', {
																model: 'DataObject',
																autoLoad: true,
																proxy: {
																	type: 'ajax',
																	url: 'listarRoles_Usuario/'+ id,
																	reader: {
																		type: 'json',
																		successProperty: 'success',
																		root: 'data',
																		messageProperty: 'message'
																	},
																	
																}       
														}),
														columns  : [ {text: "<b>Roles Asignados</b>", flex: 1, sortable: true, dataIndex: 'nombreRol'} ],
														stripeRows : true
													
													})
											],
											dockedItems: {
												xtype: 'toolbar',
												dock: 'bottom',
												items: ['->', // Fill
												{
													text: 'Guardar',
													iconCls: 'icon-save',
													handler: function(){
														grid2.getSelectionModel().selectAll();
														longitud= grid2.getSelectionModel().getSelection().length;
														lista_roles = new Array(longitud);
														i=0;
														while(i < longitud)
														{											
															lista_roles[i]=grid2.getSelectionModel().getSelection()[i].data['nombreRol'];
															i=i+1;
														}	
														grid2.getSelectionModel().deselectAll();											
														Ext.Ajax.request({
															url: 'asignarRoles_desdeABMUsuarios',
															params: {
																id_usuario: id,
																lista_roles:Ext.encode(lista_roles)
															},
															success: function() {
																Ext.Msg.show({ 		title: '<br><p align="center"><b>ALPHA MANAGER</b></p>', //<- el título del diálogo  
																					msg: 'Roles asignados correctamente', 	icon: 'ext-mb-ok',
																});	
															},
															failure: function() {
																Ext.Msg.show({	title: '<br><p align="center"><b>ALPHA MANAGER</b></p>',   
																				msg: 'Error en la asignacion de roles', 	icon: 'ext-mb-error',
																});
															}
														})
												}
												}]
											}
									}),{
									border: false
								}]
							});					
							win2.show();	

						}
					}
				}, {
                    region: 'center',
					xtype: 'writergrid',            
					itemId: 'grid',
					title: 'LISTADO DE USUARIOS ',
					flex: 1,        
					//width: 680,
					//height: 380,

					store: store,
					listeners: {
						selectionchange: function(selModel, selected) {
							win.child('#form').setActiveRecord(selected[0] || null);
						}
					}
				}		
				]
            });
            getPermisos();
            win.show();
            
    
});

    function extraer(texto, etqini, etqfin)
	{
		var ind0, ind1, parte ="";
		ind0 = texto.indexOf(etqini);
		if (ind0 >=0)
		{
			ind1 = texto.indexOf(etqfin);
		if (ind1>ind0)
			parte = texto.substring(ind0+etqini.length, ind1);
		}
		return parte;
	}

